using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using Ninject;
using RentalOfCars.Domain.Entities;
using RentalOfCars.Infrastructure.Entities;
using RentalOfCars.Server.Domain.ClientServerInterface;

namespace RentalOfCars.Client.Presentation
{
    public class AddEmployeeWindowPresenter
    {
        private readonly IKernel _kernel;
        private readonly IDbAccessSession _session;
        private readonly IAddEmployeeWindowView _view;
        private IList<IEmployeeClass> _classes;

        public AddEmployeeWindowPresenter(IAddEmployeeWindowView view, IDbAccessSession session, IKernel kernel)
        {
            _view = view;
            _session = session;
            _kernel = kernel;

            _view.OnOk = OnOk;

            UpdateAvailableClasses();
        }

        private void UpdateAvailableClasses()
        {
            _classes = _session.GetEmployeeClasses();
            var cl = new string[_classes.Count];

            for (int i = 0; i < _classes.Count; i++)
            {
                cl[i] = _classes[i].Description;
            }

            _view.AvailableClasses = cl;
        }

        private void OnOk()
        {
            var name = _view.EmployeeName;
            var lastName = _view.EmployeeLastName;
            var patronymic = _view.Patronymic;
            var login = _view.Login;
            var passport = _view.Passport;
            var phone = _view.Phone;
            var password = _view.Password;
            var classIndex = _view.SelectedClassIndex;

            var pass = name.Substring(0, 1) + lastName.Substring(0, 1) + password;
            var md5 = new MD5CryptoServiceProvider();
            var originalBytes = Encoding.UTF8.GetBytes(pass);
            var encodedBytes = md5.ComputeHash(originalBytes);
            var codedPass = BitConverter.ToString(encodedBytes);

            var employeeClass = _classes[classIndex];
            var employee = new Employee(0, name, lastName, login, patronymic, passport, phone, 0, codedPass, employeeClass,
                                        DateTime.Now, DateTime.Now);

            _session.AddEmployee(employee);

            _view.CloseWindow();
        }
    }
}